<template>
    <el-scrollbar ref="scrollbar" height="100%" class="chat-scrollbar">
        <div class="chat-container" ref="innerScrollbar">
            <div class="chat-box" ref="chatBox">
                <div v-for="(message, index) in headerStore.state.messages" :key="index" :class="['message', message.sender]">
                    <div class="content">
                        {{ message.msg }}
                    </div>
                </div>
            </div>
        </div>

    </el-scrollbar>
</template>

<script setup>
import { ref,nextTick,watch } from "vue";
import { useHeaderStore } from "../stores/header"

const headerStore = useHeaderStore()
const chatBox = ref(null);
const scrollbar = ref(null);
const innerScrollbar = ref(null);
const scrollToBottom = () => {
    nextTick(() => {
    if (scrollbar.value) {
        const max = innerScrollbar.value.clientHeight;
        scrollbar.value.setScrollTop(max);
    }
    });
};

watch(() => headerStore.state.addMessage, (newValue) =>{
    if (newValue){
        scrollToBottom();
        headerStore.state.addMessage = false;
    }
});
</script>


<style lang="less" scoped>
.chat-box {
    padding: 10px;
}

.message {
    margin: 5px 0;
    padding: 10px;
    border-radius: 4px;
}

.message.me {
    display: flex;
    flex-direction: row-reverse;

    .content {
        color: black;
        background-color: #1ba043;
        border-radius: 4px;
        padding: 6px;
    }
}

.message.other {
    display: flex;

    .content {
        background-color: #535252;
        border-radius: 4px;
        padding: 6px;
    }
}

.chat-scrollbar {
    border: 1px solid #535252;

}
</style>